using System;
using System.Collections.Generic;
using System.Web.UI;
using CodeStory.Core.ObjectEntity;
using CodeStory.Core.Services;

namespace CodeStory.Core.UI
{
	public class LayoutPage : BasePage, ILayoutPage
	{
		private PageHierarchyBuilder builder;

		public List<Control> UserControlsInPage {
			get {
				return Builder.UserControlsInPage;
			}
		}
		public PageHierarchyBuilder Builder {
			get {
				if (builder == null) {
					builder = new PageHierarchyBuilder();
					builder.Page = this;
					builder.Container = Form;
				}
				return builder; }
		}

		protected override void OnInit(EventArgs e) {
			InitializePageInternal();
			base.OnInit(e);
		}

		private void InitializePageInternal() {
			PageObject page = GetPageObject();
			if (page == null) {
				Response.Redirect("~/Error.aspx", true);
				return;
			}
			CheckPermission(page.PageID.ToString());
			InitializePage(page);
		}

		private PageObject GetPageObject() {
			string pageid = Request.QueryString["pageid"];
			string tabName = Request.QueryString["tabname"];
			PageObject page = null;
			if (!string.IsNullOrEmpty(pageid)) {
				page = PageObject.Read(new Guid(pageid));
			}
			if (page == null && !string.IsNullOrEmpty(tabName)) {
				page = PageObject.ReadFirst("PageName=@PageName", "@PageName", tabName);
			}
			if (page == null) {
				page = PageObject.ReadFirst("PageName=@PageName", "@PageName", CodeStoryConfig.DefaultPageTabName);
			}
			return page;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="page"></param>
		public void InitializePage(PageObject page) {
			string title = string.Format("{0}--{1}", CodeStorySiteSetting.Current.SiteName, page.Title);
			Title = title;
			Builder.PageObject = page;
			Builder.InitializePage();
			//Form.Controls.Add(builder.Container);


		}
	}
}